<?php

/*This code has been adapted from a tutorial at http://code.google.com/apis/kml/articles/phpmysqlkml.html#outputkml.*/

include("dbconnect.php");

// Selects all the rows in the Sighting table.
$query = 'SELECT * FROM Sighting';
$result = sqlsrv_query($sqlcon, $query);

if (!$result) 
{
  die(print_r(sqlsrv_errors(), true));
}

// Creates the Document.
$dom = new DOMDocument('1.0', 'UTF-8');


// Creates the root KML element and appends it to the root document.
$node = $dom->createElementNS('http://earth.google.com/kml/2.1', 'kml');
$parNode = $dom->appendChild($node);


// Creates a KML Document element and append it to the KML element.
$dnode = $dom->createElement('Document');
$docNode = $parNode->appendChild($dnode);


// Iterates through the MSSQL results, creating one Placemark for each row.
while($row = sqlsrv_fetch_array($result))
{
  // Creates a Placemark and append it to the Document.
  $node = $dom->createElement('Placemark');
  $placeNode = $docNode->appendChild($node);

  // Creates an id attribute and assign it the value of id column.
  $placeNode->setAttribute('id', 'placemark' . $row['ID']);

  // Create name, and description elements.
  $nameNode = $dom->createElement('name', 'Whale ID: ' . htmlentities($row['ID']));
  $placeNode->appendChild($nameNode);
  $descNode = $dom->createElement('description', '<br />Last sighted on: ' . $row['Date'] . '<br /> Long/Lat: ' . $row['End_Long'] . ' / ' . $row['End_Lat']);
  $placeNode->appendChild($descNode);
  

  // Creates a Point element.
  $pointNode = $dom->createElement('Point');
  $placeNode->appendChild($pointNode);

  // Creates a coordinates element and gives it the value of the lng and lat columns from the results.
  $coorStr = $row['End_Long'] . ','  . $row['End_Lat'];
  $coorNode = $dom->createElement('coordinates', $coorStr);
  $pointNode->appendChild($coorNode);
}

$kmlOutput = $dom->saveXML();
header('Content-type: application/vnd.google-earth.kml+xml');
echo $kmlOutput;

?>